package org.anupta.realm.server.realm;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;

import org.anupta.realm.main.Main;
import org.anupta.realm.utils.others.Config;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class RealmServer {
	private IoAcceptor acceptor = new NioSocketAcceptor();
	
	public RealmServer(){
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),LineDelimiter.NUL, new LineDelimiter("\n\0"))));
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Config.TIME_OUT);
        acceptor.setHandler(new RealmHandler());
	}
	
	public void bind(int port){
		try {
			acceptor.bind(new InetSocketAddress(Config.REALM_IP,port));
		} catch (IOException e) {
			Main.err.write(e);
		}
	}
	
	public void close(){
		acceptor.unbind();
		acceptor.dispose(true);
	}
	
	public Map<Long, IoSession> getAllSession(){
		return acceptor.getManagedSessions();
	}
}
